package cn.im.qywx.wx.component.wakeon.util;

import cn.im.qywx.system.SystemParams;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.*;

/**
 * @Description: 向指定地址发送UDP请求
 * @version V1.0
 */
@Slf4j
public class UdpUtil {
	
	public static void sendUdpMsg(String msg){
		DatagramSocket ds = null; //建立套接字udpsocket服务
		InetAddress destination = null;
		DatagramPacket dp = null;
		
		try {
			ds = new DatagramSocket(8899);//实例化套接字，指定端口号
			
			byte[] buf = msg.getBytes(); //要发送的数据
			destination = InetAddress.getByName(String.valueOf(SystemParams.UDP_PORT)); //发送的地址
			dp =  new DatagramPacket(buf, buf.length, destination , Integer.valueOf(SystemParams.UDP_IP));    
/*			destination = InetAddress.getByName(SystemParams.UDP_IP); //发送的地址
			dp =  new DatagramPacket(buf, buf.length, destination , Integer.valueOf(SystemParams.UDP_PORT));    
*/	        //打包到DatagramPacket类型中（DatagramSocket的send()方法接受此类，注意10000是接受地址的端口，不同于自己的端口！）
			ds.send(dp);  //发送数据  
			log.info("send msg to 10.121.10.180:58000. " + msg);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			log.info("open port failed. port:" + SystemParams.UDP_PORT);
			e.printStackTrace();
		} catch (UnknownHostException e) {
			log.info(" cannot find host. host:" + SystemParams.UDP_IP);
			e.printStackTrace();
		}catch (IOException e) {  
			log.info(" udp msg send failed. msg:" + msg);
			e.printStackTrace();
        }  
        ds.close();
	}
	
	public static void main(String[] args) {
		sendUdpMsg("wol-01 用户名 open");
	}
}
